package com.larissa.android.note;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.room.Room;

import com.larissa.android.note.database.NoteDao;
import com.larissa.android.note.database.NoteDatabase;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class NoteRepository {
    private static final String DATABASE_NAME="note-database";
    private static NoteRepository sNoteRepository;
    private NoteDatabase noteDatabase;
    private NoteDao noteDao;
    private Executor executor= Executors.newSingleThreadExecutor();

    private NoteRepository(Context context){
        noteDatabase= Room.databaseBuilder(context,NoteDatabase.class,DATABASE_NAME).build();
        noteDao=noteDatabase.noteDao();
    }

    public static NoteRepository getInstance(){
        if(sNoteRepository==null)
            throw new IllegalStateException("NoteRepository must be initialized");
        return sNoteRepository;
    }

    public static void initialize(Context context){
        if(sNoteRepository==null)
            sNoteRepository=new NoteRepository(context);
    }

    public LiveData<List<Note>>getAllNotes(){
        return noteDao.getAllNotes();
    }

    public void updateNote(Note note){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                noteDao.updateNote(note);
            }
        });
    }

    public void addNote(Note note){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                noteDao.addNote(note);
            }
        });
    }
}
